package de.gameduell.framework.application {
	import de.gameduell.framework.application.Application;
	import de.gameduell.framework.asset.AssetGroup;
	import de.gameduell.framework.debug.Debug;
	import de.gameduell.framework.util.FlashVars;
	import de.gameduell.net.src.communication.CommunicationEvent;
	import de.gameduell.net.src.communication.ICommunication;
	
	import flash.display.Stage;	

	public class OnlineApplication extends Application {

		private const COMMUNICATION:String = "communication";
		
		protected var communication:ICommunication;	
		
		/**  
		 * @param aStage    = the stage of the application 
		 * @param aAssets   = comprises the assets from the configfile
		 * @param aSettings = comprises the settings from the configfile
		 * @param isOnline  = is the application online or standalone
		**/	
		override public function init(aStage:Stage, aAssets:AssetGroup, aSettings:Settings, standalone:Boolean):void {
			super.init(aStage, aAssets, aSettings, standalone);
			createCommunication();
		}
		
		/**  
		 * initializes the communication with the server
		**/	
		protected function createCommunication():void {
			try {
				communication = ICommunication(assets.getAssetById(COMMUNICATION).data);
			}catch(error:Error) {
				Debug.trace("OnlineApplication::createCommunication" + settings.protocol + " error: " + error.getStackTrace(), Debug.ERROR);
			}
			try{
				communication.init(settings, FlashVars.getKeyValue("mid"));
				communication.addEventListener(CommunicationEvent.CONNECTED, onConnected);
				communication.addEventListener(CommunicationEvent.DISCONNECT, onDisconnected);
				communication.connect();
			}catch(error1:Error){
				Debug.trace("OnlineApplication::createCommunication: error: " + error1.getStackTrace(), Debug.ERROR);
			}
		}
		
		/**  
		 * is called after the connection to the server failed
		**/
		protected function onDisconnected(event:CommunicationEvent):void {
			Debug.trace("OnlineApplication::onDisconnect: APPLICATION WAS DISCONNECTED", Debug.ERROR);
		}
		
		/**  
		 * is called after the connection to the server is established
		 * and sets an according flag 
		**/
		protected function onConnected(event:CommunicationEvent):void{
			isConnected = true;
			communication.removeEventListener(CommunicationEvent.CONNECTED, onConnected);
		}
	}
}